<template>
  <a-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    :cancelText="$t('关闭')"
    v-drag
  >
    <a-spin :spinning="confirmLoading">
      <div>
        <a-form-model :rules="rules" :model="model" ref="form">
          <a-row>
            <a-col :span="24">
              <a-form-model-item :label="$t('名称')" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
                <a-input v-model="model.name" :maxLength="32" :placeholder="$t('请输入活动名称')" :disabled="disabled"></a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item :label="$t('状态')" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="state">
                <a-select :placeholder="$t('请选择状态')" v-model="model.state" :disabled="disabled">
                  <a-select-option v-for="(item, index) in stateList" :value="item.value" :key="index">
                    {{ item.title }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                :label="$t('有效期')"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                required
                style="margin-bottom: 0"
              >
                <a-row>
                  <a-col :span="10">
                    <a-form-model-item prop="beginTime">
                      <a-date-picker
                        :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                        :placeholder="$t('请选择开始日期')"
                        :disabled="disabled"
                        valueFormat="YYYY-MM-DD HH:mm:ss"
                        v-model="model.beginTime"
                        style="width: 100%"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="1" style="text-align: center"
                    ><span>~</span></a-col
                  >
                  <a-col :span="10">
                    <a-form-model-item prop="endTime">
                      <a-date-picker
                        :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                        :placeholder="$t('请选择结束日期')"
                        :disabled="disabled"
                        valueFormat="YYYY-MM-DD HH:mm:ss"
                        v-model="model.endTime"
                        style="width: 100%"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="3">
                    <a-button type="primary" @click="setLongTime">{{ $t('不限期') }}</a-button>
                  </a-col>
                </a-row>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('有效日')" required>
                <a-checkbox-group v-model="weeks" style="margin-top: 6px; margin-left: 5px" :disabled="disabled">
                  <a-checkbox style="margin-left: 8px" :value="item.key" v-for="item in allWeeksList" :key="item.key">{{
                    item.name
                  }}</a-checkbox>
                </a-checkbox-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item :label="$t('有效时段')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <template v-for="(vTime, index) in periodList">
                  <a-tag :key="index" :closable="!disabled" @close="delValidTime(index)" class="tag-active">
                    {{ vTime.beginTime + '~' + vTime.endTime }}
                  </a-tag>
                </template>
                <a-button type="link" @click="addValidTime" v-if="!isAdd" :disabled="disabled">{{
                  $t('添加')
                }}</a-button>
                <span v-else style="padding-left: 6px">
                  <a-time-picker
                    v-model="beginTime"
                    :placeholder="$t('开始时间')"
                    format="HH:mm"
                    style="width: 120px"
                    @openChange="focusTimeE"
                  />~
                  <a-time-picker
                    v-model="endTime"
                    :placeholder="$t('结束时间')"
                    format="HH:mm"
                    style="width: 120px"
                    @openChange="orgTime"
                  />
                </span>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="$t('排除日期')">
                <div>
                  <div v-for="(time, i) in excludeList" :key="i">
                    <j-date
                      date-format="YYYY-MM-DD"
                      :placeholder="$t('请选择开始日期')"
                      v-model="time.beginTime"
                      :disabled="time.timeDisabled"
                    ></j-date
                    >~
                    <j-date
                      date-format="YYYY-MM-DD"
                      :placeholder="$t('请选择结束日期')"
                      v-model="time.endTime"
                      :disabled="time.timeDisabled"
                    ></j-date>
                    <span v-if="!disabled">
                      <span>
                        <a-icon
                          v-if="time.timeDisabled"
                          @click="editTime(time)"
                          type="edit"
                          style="color: #1890ff; cursor: pointer; margin-left: 5px"
                        />
                        <a-icon
                          v-else
                          type="check"
                          @click="saveTime(time)"
                          style="color: #1890ff; cursor: pointer; margin-left: 5px"
                        />
                      </span>
                      <a-icon
                        type="close"
                        @click="delTime(time)"
                        style="color: #1890ff; cursor: pointer; margin-left: 5px"
                      />
                      <a-icon
                        type="plus"
                        v-if="i == excludeList.length - 1"
                        @click="addTime()"
                        style="color: #1890ff; cursor: pointer; margin-left: 5px"
                      />
                    </span>
                  </div>
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="acvivityType == '0' || acvivityType == '2' || acvivityType == '3'">
              <a-form-model-item :label="$t('适用会员')" required :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-checkbox
                  :indeterminate="indeterminate"
                  :checked="checkAll"
                  @change="secAllType"
                  :disabled="disabled"
                  >{{ $t('全选') }}</a-checkbox
                >
                <a-checkbox-group
                  v-model="memberTypes"
                  :disabled="disabled"
                  style="margin-top: 6px; margin-left: 5px"
                  @change="changeType"
                >
                  <a-checkbox style="margin-left: 8px" :value="item.id" v-for="item in memberList" :key="item.id">{{
                    item.name
                  }}</a-checkbox>
                </a-checkbox-group>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item :label="$t('简介')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-textarea
                  v-model="model.intro"
                  :placeholder="$t('请选择输入活动简介')"
                  :row="2"
                  :disabled="disabled"
                ></a-textarea>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="acvivityType == '0'">
              <a-form-model-item :label="$t('投币优惠')" required :labelCol="labelCol" :wrapperCol="wrapperCol">
                <div v-for="(item, index) in ruleList" :key="index">
                  <a-input-number v-model="item.coin" style="width: 100px; margin: 0 5px" :disabled="item.disabled"></a-input-number
                  >{{ $t('币') }}
                  <a-input
                    v-model="item.gameNum"
                    style="width: 100px; margin: 0 7px"
                    :disabled="item.disabled"
                  ></a-input
                  >{{ $t('局') }}
                  <span v-if="!disabled">
                    <span>
                      <a-icon
                        v-if="item.disabled"
                        @click="editRule(item)"
                        type="edit"
                        style="color: #1890ff; cursor: pointer; margin-left: 5px"
                      />
                      <a-icon
                        v-else
                        type="check"
                        @click="saveRule(item)"
                        style="color: #1890ff; cursor: pointer; margin-left: 5px"
                      />
                    </span>
                    <a-icon
                      type="close"
                      @click="delRule(item)"
                      style="color: #1890ff; cursor: pointer; margin-left: 5px"
                    />
                    <a-icon
                      type="plus"
                      v-if="index == ruleList.length - 1"
                      @click="addRule()"
                      style="color: #1890ff; cursor: pointer; margin-left: 5px"
                    />
                  </span>
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="acvivityType == '2'">
              <a-form-model-item :label="$t('活动折扣')" required :labelCol="labelCol" :wrapperCol="wrapperCol">
                <div style="display: flex; align-items: center">
                  <a-input v-model="model.discount" :placeholder="$t('请设置活动折扣')" :disabled="disabled"></a-input>%
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="acvivityType == '0' || acvivityType == '2' || acvivityType == '3'">
              <a-form-model-item
                :label="$t('适用机台')"
                required
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                style="margin-bottom: 5px; margin-left: 4px"
              >
                <div style="margin-top: 6px; margin-left: 5px">
                  <a-checkbox
                    style="width: 70px; margin-top: -10px"
                    v-model="checkAll1"
                    :disabled="disabled"
                    @change="switchSelect"
                    >{{$t('全选')}}</a-checkbox
                  >
                  <div v-for="(ele, i) in gamegroups" :key="i">
                    <a-checkbox
                      style="margin-top: -10px"
                      v-model="ele.isSelect"
                      :disabled="disabled"
                      @change="(e)=>switchSelect1(e,i)"
                      >{{ele.code+'-'+ele.name}}</a-checkbox
                    >
                    <div>
                      <a-checkbox-group v-model="ele.allowGames" :disabled="disabled" @change="(e)=>changeGame(e,i)">
                        <a-checkbox style="margin-left: 8px" :value="item.id" v-for="item in ele.gameList" :key="item.id">{{
                          item.name
                        }}</a-checkbox>
                      </a-checkbox-group>
                    </div>
                  </div>
                </div>
                <!-- <a-checkbox
                  :indeterminate="indeterminate1"
                  :checked="checkAll1"
                  @change="secAllGame"
                  :disabled="disabled"
                  >{{ $t('全选') }}</a-checkbox
                >
                <a-checkbox-group
                  v-model="games"
                  :disabled="disabled"
                  style="margin-top: 6px; margin-left: 5px"
                  @change="changeGame"
                >
                  <a-checkbox style="margin-left: 8px" :value="item.value" v-for="item in allGameList" :key="item.id">{{
                    item.title
                  }}</a-checkbox>
                </a-checkbox-group> -->
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="acvivityType == '3'">
              <a-form-model-item
                :label="$t('消费币值')"
                required
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                style="margin-bottom: 5px; margin-left: 4px"
              >
                <div>
                  <a-input-number
                    v-model="model.coin"
                    :placeholder="$t('请输入消费值')"
                    :disabled="disabled"
                    style="width: 150px"
                  ></a-input-number
                  ><span style="padding-left: 10px">{{
                    $t('（有效期内每消费满该设定值则系统自动发放相应的优惠券）')
                  }}</span>
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :span="24" v-if="acvivityType == '3'">
              <a-form-model-item
                :label="$t('赠送优惠券')"
                required
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                style="margin-bottom: 5px; margin-left: 4px"
              >
                <a-table :columns="columns" :dataSource="dataSource" bordered class="customTable" :pagination="false">
                  <template slot="action" slot-scope="text, record">
                    <a-icon type="close" v-if="!disabled" @click="deleteGoods(text, record)" />
                  </template>
                  <template slot="selectTwo" slot-scope="text, record">
                    <a-select
                      v-model="record.goodsId"
                      show-search
                      :placeholder="$t('请输入商品编码/名称')"
                      :filter-option="false"
                      :not-found-content="null"
                      @search="handleGoodsSearch"
                      :disabled="disabled"
                    >
                      <a-select-option v-for="good in addGoodsList" :key="good.id">{{ good.name }}</a-select-option>
                    </a-select>
                  </template>
                  <template slot="inputNum" slot-scope="text, record">
                    <a-input-number :disabled="disabled" v-model="record.amount" style="width: 100%;"></a-input-number>
                  </template>
                </a-table>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                :label="$t('机台限制次数')"
                required
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                style="margin-bottom: 5px; margin-left: 4px"
              >
                <div>
                  <a-input-number
                    v-model="model.limitNum"
                    :placeholder="$t('请输入机台限制次数')"
                    :disabled="disabled"
                    style="width: 150px"
                    :min="0"
                    :precision="0"
                    :max="999999999"
                  ></a-input-number
                  ><span style="padding-left: 10px">{{
                    $t('（每个会员每日在每种机台上的最大消费次数，0表示不限制）')
                  }}</span>
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                :label="$t('活动限制次数')"
                required
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                style="margin-bottom: 5px; margin-left: 4px"
              >
                <div>
                  <a-input-number
                    v-model="model.totalLimit"
                    :placeholder="$t('请输入活动限制次数')"
                    :disabled="disabled"
                    style="width: 150px"
                    :min="0"
                    :precision="0"
                    :max="999999999"
                  ></a-input-number
                  ><span style="padding-left: 10px">{{
                    $t('（每个会员允许享受该活动的最大次数，0表示不限制）')
                  }}</span>
                </div>
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-spin>
    <template slot="footer">
      <a-button @click="handleCancel">{{ disabled ? $t('关闭') : $t('取消') }}</a-button>
      <a-button @click="handleOk" v-if="!disabled" type="primary">{{ $t('保存') }}</a-button>
    </template>
  </a-modal>
</template>

<script>
import moment from 'moment'
import { httpAction, getAction } from '@/api/manage'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
let that
export default {
  name: 'AddGameActivityDetailModal',
  components: {},
  data() {
    return {
      moment,
      width: 800,
      visible: false,
      confirmLoading: false,
      title: '',
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
      model: {
        state: 1,
      },
      weeks: ['1', '2', '3', '4', '5', '6', '7'],
      rules: {
        name: [{ required: true, message: this.$t('请设置活动名称') }],
        state: [{ required: true, message: this.$t('请选择状态') }],
        beginTime: [{ required: true, message: this.$t('请选择开始日期') }],
        endTime: [{ required: true, message: this.$t('请选择结束日期') }],
      },
      stateList: [],
      disabled: false,
      acvivityType: '',
      ruleList: [],
      gameList: [],
      memberList: [],
      indeterminate: true,
      checkAll: false,
      memberTypes: [],
      allWeeksList: [
        { key: '1', name: this.$t('周一') },
        { key: '2', name: this.$t('周二') },
        { key: '3', name: this.$t('周三') },
        { key: '4', name: this.$t('周四') },
        { key: '5', name: this.$t('周五') },
        { key: '6', name: this.$t('周六') },
        { key: '7', name: this.$t('周日') },
      ],
      excludeList: [],
      periodList: [],
      weekList: [],
      indeterminate1: true,
      checkAll1: false,
      allGameList: [],
      redList: [],
      isAdd: false,
      beginTime: '',
      endTime: '',
      games: [],
      columns: [
        {
          title: this.$t('商品名称'),
          dataIndex: 'name',
          align: 'center',
          width: 340,
          scopedSlots: { customRender: 'selectTwo' },
        },
        {
          title: this.$t('数量'),
          key: 'num',
          dataIndex: 'num',
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
              },
            }
          },
          customCell: function (record, rowIndex) {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          scopedSlots: { customRender: 'inputNum' },
        },
        {
          title: '+',
          dataIndex: 'action',
          align: 'center',
          width: 30,
          customHeaderCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '25px',
                height: '32px',
                lineHeight: '32px',
                fontWeight: 'bold',
                cursor: 'pointer',
              },
              on: {
                click: () => {
                  that.addGoods()
                },
              },
            }
          },
          customCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '16px',
                height: '32px',
                lineHeight: '32px',
                fontWeight: 'bold',
                cursor: 'pointer',
              },
            }
          },
          scopedSlots: { customRender: 'action' },
        },
      ],
      dataSource: [],
      addGoodsList: [],
      giftList: [],
      gamegroups: []
    }
  },
  created() {
    that = this
  },
  methods: {
    getGameList() {
      return new Promise(resolve=>{
        getAction('game/bisGame/shopList', {}).then((res) => {
          if (res.success) {
            that.gamegroups = res.result 
          }
          resolve()
        })
      })
    },
    switchSelect(e) {
      if (that.checkAll1) {
        that.gamegroups.forEach(el=>{
          el.isSelect = true
          el.allowGames = el.gameList.map((game) => {
            return game.id
          })
        })
      }else{
        that.gamegroups.forEach(el=>{
          el.isSelect = false
          el.allowGames = []
        })
      }
    },
    switchSelect1(e,i){
      if(e.target.checked) {
        that.$set(that.gamegroups[i], 'allowGames', that.gamegroups[i].gameList.map((game) => {
          return game.id
        }))
      } else {
        that.$set(that.gamegroups[i], 'allowGames', [])
      }
      let x = that.gamegroups.findIndex(f=>{return !f.isSelect})
      if(x>-1){
        that.checkAll1 = false
      }else{
        that.checkAll1 = true
      }
    },
    changeGame(e,i){
      if(that.gamegroups[i].gameList.length == that.gamegroups[i].allowGames.length){
        that.$set(that.gamegroups[i], 'isSelect', true)
      }else{
        that.$set(that.gamegroups[i], 'isSelect', false)
      }
      let x = that.gamegroups.findIndex(f=>{return !f.isSelect})
      if(x>-1){
        that.checkAll1 = false
      }else{
        that.checkAll1 = true
      }
    },
    setLongTime() {
      that.$set(that.model, 'beginTime', moment().format('YYYY-MM-DD 00:00:00'))
      that.$set(that.model, 'endTime', moment('2099-12-31 23:59:59').format('YYYY-MM-DD 23:59:59'))
      that.$refs.form.validateField('beginTime')
      that.$refs.form.validateField('endTime')
    },
    add(value) {
      that.weeks = ['1', '2', '3', '4', '5', '6', '7']
      that.model = {
        state: 1,
        type: value,
        limitNum: 0,
        totalLimit: 0
      }
      that.edit(that.model)
    },
    async edit(record, state) {
      if (state) {
        that.title = that.$t('查看')
      } else {
        that.title = that.$t('编辑')
      }
      that.disabled = state ? state : false
      that.acvivityType = record.type
      that.weekList = []
      that.giftList = []
      that.dataSource = []
      that.ruleList = []
      that.redList = []
      that.games = []
      that.gameList = []
      that.allGameList = []
      that.memberList = []
      that.memberTypes = []
      that.excludeList = []
      that.periodList = []
      that.checkAll = false
      that.indeterminate = false
      that.checkAll1 = false
      that.indeterminate1 = false
      that.model = Object.assign({}, record)
      that.model.state = '' + that.model.state
      that.visible = true
      that.$nextTick(() => {
        that.$refs.form.clearValidate()
      })
      initDictOptions('bis_activity.state').then((res) => {
        if (res.success) {
          that.stateList = res.result
        }
      })
      await that.getMemberList()
      await that.getGameList()
      if (that.model.id) {
        if (that.acvivityType == '0' || that.acvivityType == '2' || that.acvivityType == '3') {
          that.memberTypes = that.model.memberType.split(',')
          if (that.memberTypes.length == that.memberList.length) {
            that.checkAll = true
          } else {
            that.checkAll = false
          }
          that.indeterminate = false
          if (that.acvivityType == '0') {
            getAction('/gameactivity/bisGameActivity/queryBisGameActivityDiscountByMainId', { id: that.model.id }).then(
              (res) => {
                if (res.success) {
                  that.ruleList = res.result
                  that.ruleList.forEach((col) => {
                    that.$set(col, 'disabled', true)
                  })
                  if (!that.disabled && that.ruleList.length == 0) {
                    if (that.ruleList.length == 0) {
                      let aa = {}
                      aa.coin = ''
                      aa.gameNum = ''
                      aa.disabled = false
                      that.ruleList.push(aa)
                    }
                  }
                }
              }
            )
          }
          if (that.acvivityType == '2') {
            getAction('/gameactivity/bisGameActivity/queryBisGameActivityReductionByMainId', {
              id: that.model.id,
            }).then((res) => {
              if (res.success) {
                that.redList = res.result
                if (that.redList.length > 0) {
                  that.$set(that.model, 'discount', that.redList[0].discount)
                }
              }
            })
          }
          if (that.acvivityType == '3') {
            that.addGoodsList = []
            getAction('/gameactivity/bisGameActivity/queryBisGameActivityGiftMainId', {
              id: that.model.id,
            }).then((res) => {
              if (res.success) {
                that.giftList = res.result
                if (that.giftList.length > 0) {
                  that.model.coin = that.giftList[0].coin
                  that.dataSource = that.giftList[0].detailList
                  that.giftList[0].detailList.forEach((dtl) => {
                    that.addGoodsList.push({
                      id: dtl.goodsId,
                      name: dtl.goodsName,
                    })
                  })
                }
              }
            })
          }
          getAction('/gameactivity/bisGameActivity/queryBisGameActivityGameByMainId', { id: that.model.id }).then(
            (res) => {
              if (res.success) {
                that.initGame(res.result, 0)
              }
            }
          )
          getAction('gameactivity/bisGameActivity/queryBisGameActivityExcludeByMainId', { id: that.model.id }).then(
            (res) => {
              if (res.success) {
                that.excludeList = res.result
                if (that.excludeList.length == 0) {
                  let aa = {}
                  aa.beginTime = ''
                  aa.endTime = ''
                  aa.timeDisabled = that.disabled
                  that.excludeList.push(aa)
                } else {
                  that.excludeList.forEach((col) => {
                    that.$set(col, 'timeDisabled', true)
                  })
                }
              }
            }
          )
          getAction('/gameactivity/bisGameActivity/queryBisGameActivityPeriodByMainId', { id: that.model.id }).then(
            (res) => {
              if (res.success) {
                that.periodList = res.result
              }
            }
          )
          getAction('/gameactivity/bisGameActivity/queryBisGameActivityWeekByMainId', { id: that.model.id }).then(
            (res) => {
              if (res.success) {
                that.weekList = res.result
                let arr = res.result.map((r) => {
                  return '' + r.week
                })
                that.weeks = arr
              }
            }
          )
        }
      } else {
        that.getGoodsList()
        if (!that.disabled) {
          if (that.ruleList.length == 0) {
            let aa = {}
            aa.coin = ''
            aa.gameNum = ''
            aa.disabled = false
            that.ruleList.push(aa)
          }
          if (that.excludeList.length == 0) {
            let aa = {}
            aa.beginTime = ''
            aa.endTime = ''
            aa.timeDisabled = false
            that.excludeList.push(aa)
          }
        }
      }
    },
    initGame(list, i){
      if(i <= that.gamegroups.length - 1){
        let arr = that.gamegroups[i].gameList.filter(item1 => 
          list.some(item2 => item1.id === item2.gameId)
        ).map(item => item.id);
        that.$set(that.gamegroups[i], 'allowGames', arr)
        if(arr.length == that.gamegroups[i].gameList.length){
          that.$set(that.gamegroups[i], 'isSelect', true)
        }else{
          that.$set(that.gamegroups[i], 'isSelect', false)
        }
        i++;
        that.initGame(list, i)
      }else{
        let x = that.gamegroups.findIndex(f=> !f.isSelect)
        if(x>-1){
          that.checkAll1 = false
        }else{
          that.checkAll1 = true
        }
      }
    },
    editTime(item) {
      that.$set(item, 'timeDisabled', false)
    },
    saveTime(item) {
      let i = 0
      if (item.beginTime > item.endTime) {
        that.$message.warning(that.$t('排除日期-结束日期应晚于开始日期'))
        return
      }
      that.excludeList.forEach((col) => {
        if (col.beginTime != item.beginTime && col.endTime != item.endTime) {
          i++
        } else {
          i--
        }
      })
      if (i == that.excludeList.length - 2) {
        that.$set(item, 'timeDisabled', true)
      } else {
        that.$message.warning(that.$t('已存在重复的排除日期'))
      }
    },
    addTime() {
      let obj = {}
      obj.beginTime = ''
      obj.endTime = ''
      obj.timeDisabled = false
      that.excludeList.push(obj)
    },
    delTime(item) {
      that.excludeList.forEach((col) => {
        if (col.beginTime == item.beginTime && col.endTime == item.endTime) {
          let index = that.excludeList.indexOf(item)
          that.excludeList.splice(index, 1)
        }
      })
      if (that.excludeList.length == 0) {
        let obj = {}
        obj.beginTime = ''
        obj.endTime = ''
        obj.timeDisabled = false
        that.excludeList.push(obj)
      }
    },
    addValidTime() {
      that.isAdd = !that.isAdd
    },
    delValidTime(ind) {
      that.periodList.splice(ind, 1)
    },
    focusTimeE(bol) {
      if (!bol && !that.beginTime) {
        that.$message.warn('请选择开始时间')
      }
    },
    orgTime(bol) {
      if (!bol) {
        if (!that.beginTime) {
          that.$message.warn('请选择开始时间')
          return
        }
        if (!that.endTime) {
          that.$message.warn('请选择开始时间')
          return
        }
        if (that.beginTime > that.endTime) {
          that.$message.warn('该时间段冲突！')
          return
        }
        that.isAdd = false
        that.periodList.push({
          beginTime: moment(that.beginTime).format('HH:mm'),
          endTime: moment(that.endTime).format('HH:mm'),
        })
        that.beginTime = ''
        that.endTime = ''
      }
    },
    getMemberList() {
      return new Promise((resolve) => {
        getAction('/member/bisMemberRule/list', { notNonmember: 1, manageState: 'Y', pageSize: 40 }).then((res) => {
          if (res.success) {
            that.memberList = res.result.records
            if (!that.model.id) {
              that.memberTypes = that.memberList.map((m) => {
                return m.id
              })
              that.checkAll = true
            }
          }
          resolve()
        })
      })
    },
    editRule(item) {
      that.$set(item, 'disabled', false)
    },
    saveRule(item) {
      let i = 0
      that.ruleList.forEach((col) => {
        if (
          (col.coin == item.coin && col.gameNum == item.gameNum) ||
          col.coin == item.coin ||
          col.gameNum == item.gameNum
        ) {
          i--
        } else {
          i++
        }
      })
      if (i == that.ruleList.length - 2) {
        that.$set(item, 'disabled', true)
      } else {
        that.$message.warning(that.$t('已存在重复的投币优惠规则'))
      }
    },
    addRule() {
      let obj = {}
      obj.coin = ''
      obj.gameNum = ''
      obj.disabled = false
      that.ruleList.push(obj)
    },
    delRule(item) {
      if (that.ruleList.length == 1) {
        that.$message.warning(that.$t('至少设置一条投币优惠规则'))
        return
      } else {
        that.ruleList.forEach((col) => {
          if (col.coin == item.coin && col.gameNum == item.gameNum) {
            let index = that.ruleList.indexOf(item)
            that.ruleList.splice(index, 1)
          }
        })
      }
    },
    handleOk() {
      that.$refs.form.validate((valid) => {
        if (valid) {
          let query = {}
          query = that.model
          if (that.memberTypes.length == 0) {
            that.$message.warning(that.$t('至少选择一种会员'))
            return
          }
          query.memberType = that.memberTypes.join(',')
          if (moment(that.model.beginTime) >= moment(that.model.endTime)) {
            that.$message.warning(that.$t('结束日期应晚于开始日期'))
            return
          }
          if (that.weeks.length == 0) {
            that.$message.warning(that.$t('至少选择一个有效日'))
            return
          }
          let arr = that.weeks.map((w) => {
            let dtl = {
              week: w,
            }
            let obj = that.weekList.find((wl) => {
              return wl.week == w
            })
            if (obj) {
              dtl = Object.assign({}, dtl, obj)
            }
            return dtl
          })
          query.weekList = arr
          let excludeList = []
          that.excludeList.forEach((col) => {
            if (col.timeDisabled) {
              let dtl = Object.assign({}, col)
              dtl.beginTime = moment(dtl.beginTime).format('YYYY-MM-DD 00:00:00')
              dtl.endTime = moment(dtl.endTime).format('YYYY-MM-DD 23:59:59')
              delete dtl.timeDisabled
              excludeList.push(dtl)
            }
          })
          if (excludeList.length > 0) {
            query.excludeList = excludeList
          }
          query.periodList = that.periodList
          let ruleList = []
          if (that.acvivityType == '0') {
            let i = 0
            that.ruleList.forEach((col) => {
              if (col.disabled) {
                ruleList.push(col)
              } else {
                i++
              }
            })
            if (i != 0) {
              that.$message.warning(that.$t('请添加投币优惠规则'))
              return
            }
          }
          query.bisGameActivityDiscountList = ruleList
          let gameArr = that.gamegroups.reduce((acc, item) => {
            return acc.concat(item.allowGames);
          }, []);
          if ((that.acvivityType == '0' || that.acvivityType == '2') && gameArr.length == 0) {
            that.$message.warning(that.$t('至少选择一个机台'))
            return
          }
          /* that.games.forEach((g) => {
            let x = that.gameList.findIndex((gm) => {
              return g == gm.gameId
            })
            if (x > -1) {
              gameArr.push(that.gameList[x])
            } else {
              gameArr.push({
                gameId: g,
              })
            }
          }) */
          query.bisGameActivityGameList = gameArr.map(g=>{return {gameId: g}})
          console.log(query.bisGameActivityGameList)
          if (
            that.acvivityType == '2' &&
            (that.model.discount === undefined || that.model.discount === 'undefined' || that.model.discount === null || that.model.discount === 'null' || that.model.discount === '')
          ) {
            that.$message.warning(that.$t('请设置活动折扣'))
            return
          }
          if (that.acvivityType == '2') {
            if (that.redList.length > 0) {
              that.redList[0].discount = that.model.discount
            } else {
              that.redList = [
                {
                  discount: that.model.discount,
                },
              ]
            }
            query.redList = that.redList
          }
          if (that.acvivityType == '3' && !that.model.coin) {
            that.$message.warning(that.$t('请设置消费币值'))
            return
          }
          let arr0 = that.dataSource.filter((d) => {
            return d.goodsId
          })
          if (that.acvivityType == '3' && arr0.length == 0) {
            that.$message.warning(that.$t('请设置优惠券'))
            return
          }
          if (that.acvivityType == '3') {
            if (that.giftList.length > 0) {
              that.giftList[0].coin = that.model.coin
              that.giftList[0].detailList = arr0
            } else {
              that.giftList = [
                {
                  coin: that.model.coin,
                  detailList: arr0,
                },
              ]
            }
            query.giftList = that.giftList
          }
          that.confirmLoading = true
          let url = ''
          let method = 'post'
          if (that.model.id) {
            url = '/gameactivity/bisGameActivity/edit'
          } else {
            url = '/gameactivity/bisGameActivity/add'
          }
          httpAction(url, query, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.close()
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
    handleCancel() {
      that.close()
    },
    close() {
      that.visible = false
    },
    secAllType(e) {
      let arr = that.memberList.map((m) => {
        return m.id
      })
      Object.assign(that, {
        memberTypes: e.target.checked ? arr : [],
        indeterminate: false,
        checkAll: e.target.checked,
      })
    },
    changeType(checkedList) {
      that.indeterminate = !!checkedList.length && checkedList.length < that.memberList.length
      that.checkAll = checkedList.length === that.memberList.length
    },
    secAllGame(e) {
      let arr = that.allGameList.map((m) => {
        return m.value
      })
      Object.assign(that, {
        games: e.target.checked ? arr : [],
        indeterminate1: false,
        checkAll1: e.target.checked,
      })
    },
    /* changeGame(checkedList) {
      that.indeterminate1 = !!checkedList.length && checkedList.length < that.allGameList.length
      that.checkAll1 = checkedList.length === that.allGameList.length
    }, */
    handleGoodsSearch(value) {
      that.getGoodsList(value)
    },
    getGoodsList(value) {
      that.addGoodsList = []
      let querydata = {}
      querydata.pageIndex = 1
      querydata.pageSize = 10
      querydata.form = 9
      querydata.goodsInfo = value
      getAction('/goods/bisGoodsInfor/list', querydata).then((res) => {
        if (res.success) {
          that.addGoodsList = res.result.records
        }
      })
    },
    addGoods() {
      if (!that.disabled) {
        let obj = {
          goodsId: undefined,
          amount: 1,
        }
        that.dataSource.push(obj)
      }
    },
    deleteGoods(a, b) {
      that.dataSource.forEach((col) => {
        if (col.goodsId == b.goodsId) {
          let index = that.dataSource.indexOf(col)
          that.dataSource.splice(index, 1)
        }
      })
    },
  },
}
</script>
<style>
.batchForm .ant-form-item-label {
  width: 30%;
}
.batchForm .ant-form-item-control-wrapper {
  width: 62.5%;
}
</style>